﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;

namespace SourceRestore.IconHandler
{
    #region SHFILEINFO structure
    [StructLayout(LayoutKind.Sequential), CLSCompliant(false)]
    public struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    };
    #endregion

    #region Win32 class
    internal class Win32
    {
        public const uint SHGFI_ICON = 0x100;
        public const uint SHGFI_LARGEICON = 0x0;    // 'Large icon
        public const uint SHGFI_SMALLICON = 0x1;    // 'Small icon
        public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute

        [DllImport("shell32.dll")]
        public static extern IntPtr SHGetFileInfo(string pszPath,
            uint dwFileAttributes,
            ref SHFILEINFO psfi,
            uint cbSizeFileInfo,
            uint uFlags);
        [DllImport("User32.dll")]
        public static extern int DestroyIcon(System.IntPtr hIcon);
    }
    #endregion

    public class GetFileAssociatedIcon
    {
        //private string mFileName;
        //IntPtr hImgSmall;    //the handle to the system image list
        //IntPtr hImgLarge;    //the handle to the system image list

        static GetFileAssociatedIcon()
        {
            //mFileName = fileName;
        }

        public static Icon GetFileIcon(string fileName)
        {
            //IntPtr hImgSmall;
            System.Drawing.Icon fileIcon = null;
            SHFILEINFO shinfo;
            try
            {
                shinfo = new SHFILEINFO();
                Win32.SHGetFileInfo(fileName, 0, ref shinfo,
                    (uint)Marshal.SizeOf(shinfo),
                    Win32.SHGFI_ICON |
                    Win32.SHGFI_SMALLICON |
                    Win32.SHGFI_USEFILEATTRIBUTES);
                fileIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
                fileIcon = (Icon)fileIcon.Clone();
                Win32.DestroyIcon(shinfo.hIcon);
            }
            catch
            {
                fileIcon = null;
            }
            return fileIcon;
        }
    }
}
